package com.onetech.adrewards.free.models;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;

import com.onetech.adrewards.free.OneTech_ApplicationContext;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.config.AppConfig.URLRequestApi;
import com.onetech.adrewards.free.http.APIRequestResult;
import com.onetech.adrewards.free.http.ZuZuHttpRequest;
import com.onetech.adrewards.free.listener.CommonIF;
import com.onetech.adrewards.free.objects.InviteFriendDTO;
import com.onetech.adrewards.free.objects.InvitedFriendDTO;
import com.onetech.adrewards.free.objects.MailDomainDTO;
import com.onetech.adrewards.free.objects.RegisterSuccessDTO;
import com.onetech.adrewards.free.objects.ResultDTO;
import com.onetech.adrewards.free.objects.SlideDTO;
import com.onetech.adrewards.free.objects.SocialShareDTO;
import com.onetech.adrewards.free.objects.StartUpDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.zuzu.db.store.SimpleStoreIF;


public class CommonModel implements CommonIF {
	private static CommonIF _instance;
	private static final Lock createLock = new ReentrantLock();
	private static final int STORE_EXPIRE = -1;
	
	
	public CommonModel() {
		getStoreAdapter();
	}

	public static CommonIF getInstance() {
		if (_instance == null) {
			createLock.lock();
			if (_instance == null) {
				_instance = new CommonModel();
			}
			createLock.unlock();
		}
		return _instance;
	}
	private SimpleStoreIF getStoreAdapter() {
		return AdrewadsUtils.getStoreAdapter(Cache.COMMON_NAME,
				OneTech_ApplicationContext.getContext(), Cache.COMMON_NUMBER);
	}
	@Override
	public void setStore(String key, String value) {
		try {
			this.getStoreAdapter().put(key, value, STORE_EXPIRE);
		} catch (Exception e) {
		}		
	}
	@Override
	public void setStore(String key, String value,int expiredTime) {
		try {
			this.getStoreAdapter().put(key, value, expiredTime);
		} catch (Exception e) {
		}		
	}
	@Override
	public String getStore(String key){
		String result=null;
		try {
			result = getStoreAdapter().get(key);
			if(result!=null && result.trim().length()<1){
				result=null;
			}
		} catch (Exception e) {
			result=null;
		}
		return result;
	}
	
	
	
	@Override
	public RegisterSuccessDTO registerInviteCode(String inviteCode){
		RegisterSuccessDTO result=null;
		Bundle mBundle=new Bundle();
		mBundle.putString("invite_code", inviteCode);
		
		String encrypt=AdrewadsUtils.convert2SHA1(AppConfig.deviceInfo.getDevice_Id() +inviteCode+AppConfig.apiAppKey);
		mBundle.putString("encrypt", encrypt);
		//post to server
		//String msg = "";
		// try {
           //  if (gcm == null) {
               //  gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
            // }
           //  regid = gcm.register(PROJECT_NUMBER);
           //-//  msg = "Device registered, registration ID=" + regid;
            // Log.i("GCM",  msg);

        // } catch (Exception ex) {
           //  msg = "Error :" + ex.getMessage();

       //  }
		APIRequestResult data= ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_REGISTER_INVITE_CODE,mBundle);
		if(data==null){
			return null;
		}
		try {
			if(!data.error_code.equals("0"))
			{
				result=new RegisterSuccessDTO();
				result.setError_code(data.error_code);
				result.setError_message(data.error_msg);
	
			} else if (data.data != null && !data.data.equals("")) {
				result=new RegisterSuccessDTO();
				result.setError_code(data.error_code);
				result.setError_message(data.error_msg);
				
				JSONObject jb=(JSONObject)data.data;				
				result.setMem_id(jb.getString("mem_id"));
				result.setToken(jb.getString("token"));
				
				JSONObject jObject=jb.getJSONObject("result");
				
				//result.setAccum_coin(jObject.getInt("accum_coin"));
				result.setTotal_coin(jObject.getInt("total_coin"));
				result.setAlert(jObject.getString("alert"));
				
				result.setLogin_bonus_flag(jObject.getString("login_bonus_flag"));
				result.setBonus_max_coin(jObject.getString("bonus_max_coin"));
				result.setExchange_coin_limit(jObject.getString("exchange_coin_limit"));
				
				setStore(Cache.ONE_TECH_USER_ID, result.getMem_id());
				setStore(Cache.ONE_TECH_USER_POINTS, String.valueOf(result.getTotal_coin()));
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public ResultDTO doSocialCoin(String type){
		
		Bundle mBundle=new Bundle();
		mBundle.putString("type", type);
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_SOCIAL_COIN + AppConfig.uId, mBundle);
		
		try {
			result=new ResultDTO(data);
			
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public List<SocialShareDTO> getSocialShareBonus(){
		
		Bundle mBundle=new Bundle();
		
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_SOCIAL_SHARE + AppConfig.uId, mBundle);
		return parserSocialShareDTO(data);
		
		
	}
	
	
	@Override
	public ResultDTO sendMailInvite(String inviteCode, String email){
		
		Bundle mBundle=new Bundle();
		mBundle.putString("invite_code", inviteCode);
		mBundle.putString("email", email);
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_SENDMAIL_INVITE_CODE+AppConfig.uId, mBundle);
		
		try {
			result=new ResultDTO(data);
			
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	@Override
	public ResultDTO registerEmail(String email){
		
		Bundle mBundle=new Bundle();
		
		mBundle.putString("email", email);
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_SENDMAIL+AppConfig.uId, mBundle);
		
		try {
			result=new ResultDTO(data);
			
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	@Override
	public ResultDTO doInviteCoin(String inviteCode){
		
		Bundle mBundle=new Bundle();
		mBundle.putString("invite_code", inviteCode);
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_INVITE_COIN + AppConfig.uId, mBundle);
		
		try {
			result=new ResultDTO(data);
			
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public ResultDTO doReviewBonus(){
		
		Bundle mBundle=new Bundle();
		
		ResultDTO result =null;
		APIRequestResult data = ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.GET_REVIEW_COIN + AppConfig.uId, mBundle);
		
		try {
			result=new ResultDTO(data);
			
		}catch(Exception ex){
			return null;
		}
		return result;
	}

	
	
	
	@Override
	public InviteFriendDTO getInviteFriendInfo(){
		InviteFriendDTO result=null;
		AdrewadsUtils.checkUId();
		APIRequestResult data= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_INVITE_FRIEND_INFO+AppConfig.uId ,new Bundle());		
		if(data==null){
			return null;
		}
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jb=(JSONObject)data.data;
				JSONObject temp = jb.getJSONObject("result");
				result=new InviteFriendDTO();
				if(temp!=null ){
					
					result.invite_exp=temp.getString("invite_exp");
					result.invite_msg=temp.getString("invite_msg");
					
					result.invited_coin=temp.getString("invited_coin");
					result.inviter_coin=temp.getString("inviter_coin");
					result.msg1=temp.getString("msg1");
					result.msg2=temp.getString("msg2");
					result.msg3=temp.getString("msg3");
					result.invite_code = temp.getString("invite_code");
				}
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public InvitedFriendDTO getInvitedFriendInfo(){
		InvitedFriendDTO result=null;
		AdrewadsUtils.checkUId();
		APIRequestResult data= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_INVITED_FRIEND_INFO ,new Bundle());		
		if(data==null){
			return null;
		}
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jb=(JSONObject)data.data;
				JSONObject temp = jb.getJSONObject("result");
				result=new InvitedFriendDTO();
				if(temp!=null ){
					
					result.msg=temp.getString("msg");
					result.note=temp.getString("notes");
					
					String domains = temp.getString("mail_domain");
					result.mailDomain = new ArrayList<String>();
					if(!TextUtils.isEmpty(domains))
					{
						for(String item : domains.split(","))
						{
							result.mailDomain.add(item);
						}
					}
					
				}
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public MailDomainDTO getMailDomain(){
		MailDomainDTO result=null;
		AdrewadsUtils.checkUId();
		APIRequestResult data= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_MAIL_DOMAIN ,new Bundle());		
		if(data==null){
			return null;
		}
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jb=(JSONObject)data.data;
				JSONObject temp = jb.getJSONObject("result");
				result=new MailDomainDTO();
				if(temp!=null ){
					
					result.msg=temp.getString("msg");
					result.note=temp.getString("notes");
					
					String domains = temp.getString("mail_domain");
					result.mailDomain = new ArrayList<String>();
					if(!TextUtils.isEmpty(domains))
					{
						for(String item : domains.split(","))
						{
							result.mailDomain.add(item);
						}
					}
					
				}
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	@Override
	public List<SlideDTO> getExchangeBanner(){		
		APIRequestResult data= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_EXCHANGE_BANNER ,new Bundle());
		return parserSlideDTO(data);
	}
	@Override
	public List<SlideDTO> getSliderBanner(){
		
		APIRequestResult data= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_SLIDE_BANNER_HOME ,new Bundle());
		return parserSlideDTO(data);
	}
	
	private List<SlideDTO> parserSlideDTO(APIRequestResult data){
	
		List<SlideDTO> result=null;
		if(data==null){
			return null;
		}
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {			 
				JSONObject jb=(JSONObject)data.data;
				JSONArray jArr=jb.getJSONArray("result");
				result=new ArrayList<SlideDTO>();
				for (int i = 0; i < jArr.length(); i++) {
					JSONObject temp=jArr.getJSONObject(i);
					SlideDTO slide=new SlideDTO();
					slide.id=temp.getString("id");
					slide.img=temp.getString("img");
					slide.type=temp.getString("type");
					
					slide.url=temp.getString("url");
					result.add(slide);
				}
			}else{
				return null;
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	
	/**
	 * Get social data
	 * @param data
	 * @return
	 */
	private List<SocialShareDTO> parserSocialShareDTO(APIRequestResult data){
		
		List<SocialShareDTO> result=null;
		if(data==null){
			return null;
		}
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {			 
				JSONObject jb=(JSONObject)data.data;
				JSONArray jArr=jb.getJSONArray("result");
				result = new ArrayList<SocialShareDTO>();
				for (int i = 0; i < jArr.length(); i++) {
					JSONObject temp=jArr.getJSONObject(i);
					SocialShareDTO slide=new SocialShareDTO();
					slide.id=temp.getString("id");
					slide.type = temp.getString("type");
					slide.iconUrl = temp.getString("icon_url");
					slide.description = temp.getString("description");
					slide.bonus = temp.getString("coin");
					slide.title = temp.getString("title");
					slide.shareText = temp.getString("share_text");
					result.add(slide);
				}
			}else{
				return null;
			}
		}catch(Exception ex){
			return null;
		}
		return result;
	}
	
	
	@Override
	public StartUpDTO getStartUpData(String uId,boolean isStartUp) {
		Bundle params=new Bundle();
		String setStartUp="";
		if(isStartUp && (uId!=null)){
			setStartUp="/"+uId+"?start=true";
			AdrewadsUtils.setFirstStartUp(true);
		}
		APIRequestResult result= ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_START_UP_INFO + setStartUp ,params);
		return parserStartUpData(result);
	}
	private StartUpDTO parserStartUpData(APIRequestResult data){
		StartUpDTO result=null;
		if(data==null){
			return null;
		}
		try {
			result=new StartUpDTO();
			result.setErr_code(data.error_code);
			result.setErr_message(data.error_msg);
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jb=(JSONObject)data.data;
				result.setToken(jb.getString("token"));
				result.setMem_id(jb.getString("mem_id"));
				
				JSONObject jbObject=jb.getJSONObject("result");
				result.setId(jbObject.getString("id"));
				//result.setForce_update_url(jbObject.getString("force_update_url"));
				result.setNew_version_flag(jbObject.getString("new_version_flag"));
				result.setUpdated_at(jbObject.getString("updated_at"));
				result.setNew_version_url(jbObject.getString("new_version_url"));
				result.setMaintenance_flag(jbObject.getString("maintenance_flag"));
				result.setBonus_max_coin(jbObject.getString("bonus_max_coin"));
				result.setCreated_at(jbObject.getString("created_at"));
				result.setForce_update_flag(jbObject.getString("force_update_flag"));
				result.setForce_update_target_version(jbObject.getString("force_update_target_version"));	
				result.setExchange_coin_limit(jbObject.getString("exchange_coin_limit"));
				result.setTotal_coin(jbObject.optString("total_coin").trim());
				result.setLogin_bonus_flag(jbObject.getString("login_bonus_flag"));
				result.setAd_sort(jbObject.getString("ad_sort"));
				
				setStore(Cache.ONE_TECH_USER_ID, result.getMem_id());
				setStore(Cache.ONE_TECH_USER_POINTS, result.getTotal_coin());

			}
		} catch (Exception e) {
		}
		return result;
	}

	@Override
	public APIRequestResult getBonusLogin() {
		Bundle params=new Bundle();
		AdrewadsUtils.checkUId();
		return ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_BONUS_FOR_LOGIN+AppConfig.uId,params);		
		//return parserBonusLogin(result);
	}
	private int parserBonusLogin(APIRequestResult data){
		int result=-1;
		try {
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jsonObject=(JSONObject)data.data;
				result = jsonObject.getJSONObject("result").getInt("coin_bonus");
			}
		} catch (Exception e) {
		}
		return result;
	}
	
}
